/******************************************************************************
 * Copyright (C) 671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODECPP_FOUNDATION_LOCKEDQUEUE_H_
#define NODECPP_FOUNDATION_LOCKEDQUEUE_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <cassert>
#include <deque>
#include <NodeCpp/Macros.h>
#include <NodeCpp/LockGuard.h>
#include <NodeCpp/Mutex.h>

namespace NodeCpp
{
	template< typename T, typename MUTEX = Mutex, typename StorageType = std::deque<T> >
	class LockedQueue
	{
	public:
		LockedQueue(void)
			: Lock_()
			, Queue_()
			, Canceled_(false)
		{
		}
		virtual ~LockedQueue(void)
		{
		}


		void Add(const T& _Item)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			Queue_.push_back(_Item);
		}

		bool Next(T& _Result)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			if (Queue_.empty()) {
				return false;
			}
			_Result = Queue_.front();
			Queue_.pop_front();
			return true;
		}

		template<class Checker>
		bool Next(T& _Result, Checker& _Check)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			if (Queue_.empty()) {
				return false;
			}
			_Result = Queue_.front();
			if (!_Check.Process(_Result)) {
				return false;
			}
			Queue_.pop_front();
			return true;
		}

		T& Peek(void)
		{
			Lock();
			T& _Result = Queue_.front();
			return _Result;
		}

		void Cancel(void)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			Canceled_ = true;
		}

		bool IsCancelled(void)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			return Canceled_;
		}

		void Lock(void) { this->Lock_.lock(); }
		void Unlock(void) { this->Lock_.unlock(); }

		bool Empty(void)
		{
			NODECPP_LOCK_MUTEX(_Guard, Lock_);
			return Queue_.empty();
		}

	private:
		MUTEX Lock_;
		StorageType Queue_;
		volatile bool Canceled_;
	};
}

#endif // NODECPP_FOUNDATION_LOCKEDQUEUE_H_
